import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/auth";
import { getDb } from "@/db";
import { apiKey } from "@/db/api-key.schema";
import { generateApiKey, hashApiKey, getApiKeyPrefix } from "@/lib/api-key";
import { eq, and } from "drizzle-orm";

// GET /api/keys - List user's API keys
export async function GET(request: NextRequest) {
  try {
    const session = await auth();

    if (!session?.user?.id) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const db = await getDb();
    const userKeys = await db
      .select({
        id: apiKey.id,
        name: apiKey.name,
        keyPrefix: apiKey.keyPrefix,
        createdAt: apiKey.createdAt,
        updatedAt: apiKey.updatedAt,
      })
      .from(apiKey)
      .where(
        and(
          eq(apiKey.ownerType, "user"),
          eq(apiKey.ownerId, session.user.id)
        )
      )
      .orderBy(apiKey.createdAt);

    return NextResponse.json({ keys: userKeys });
  } catch (error) {
    console.error("Error fetching API keys:", error);
    return NextResponse.json(
      { error: "Internal server error" },
      { status: 500 }
    );
  }
}

// POST /api/keys - Create new API key
export async function POST(request: NextRequest) {
  try {
    const session = await auth();

    if (!session?.user?.id) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const { name } = await request.json();

    if (!name || typeof name !== "string" || name.trim().length === 0) {
      return NextResponse.json(
        { error: "Name is required" },
        { status: 400 }
      );
    }

    // Generate the API key
    const fullKey = generateApiKey();
    const keyHash = hashApiKey(fullKey);
    const keyPrefix = getApiKeyPrefix(fullKey);

    // Store the hashed key
    const db = await getDb();
    const [newKey] = await db
      .insert(apiKey)
      .values({
        ownerType: "user",
        ownerId: session.user.id,
        name: name.trim(),
        keyHash,
        keyPrefix,
      })
      .returning({
        id: apiKey.id,
        name: apiKey.name,
        keyPrefix: apiKey.keyPrefix,
        createdAt: apiKey.createdAt,
      });

    // Return the full key only once (during creation)
    return NextResponse.json({
      key: newKey,
      fullKey, // This is the only time the full key will be returned
    });
  } catch (error) {
    console.error("Error creating API key:", error);
    return NextResponse.json(
      { error: "Internal server error" },
      { status: 500 }
    );
  }
}